<template>
  <BaseDialog
    ref="dialogRef"
    dialogTitle="批量操作角色"
    dialogWidth="600px"
    :dialogBodyStyle="{ height: '60vh', overflow: 'auto' }"
    @dialog-submit="transferDepartment"
    >>
    <template #dialog_body>
      <!--部门-->
      <el-form label-width="auto" ref="formRef" :model="form">
        <el-form-item label="部门">
          <SysDepartmentTreeSelect v-model="form.departmentId" :data="departmentTree" :is-remote="false" />
        </el-form-item>
      </el-form>
      <!--账户列表-->
      <el-table
        ref="tableRef"
        :data="users"
        row-key="id"
        table-layout="fixed"
        @selection-change="handleSelectionChange"
        highlight-current-row
        stripe
        border
        max-height="400px"
      >
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column align="center" type="index" fixed />
        <el-table-column show-overflow-tooltip prop="username" label="账户名" />
        <el-table-column show-overflow-tooltip prop="nickName" label="网名" />
        <el-table-column show-overflow-tooltip prop="departmentName" label="部门">
          <template #default="scope">
            {{ scope.row.department != null ? scope.row.department.name : '' }}
          </template>
        </el-table-column>
      </el-table>
    </template>
  </BaseDialog>
</template>

<script setup lang="ts">
import BaseDialog from '@/components/base/dialog/BaseDialogComponent.vue';
// 导入部门选择组件
import SysDepartmentTreeSelect from '@/components/auth/SysDepartmentTreeSelectComponent.vue';
import type { Role, User } from '@/types/interface/auth_interface';
import { inject, nextTick, ref } from 'vue';
import { userSexDict, dictToMap } from '@/api/dict';
import { ElMessage } from 'element-plus';
import Request from '@/api/request/request';
import urls from '@/api/request/urls';
import type { ResponseData, TreeData } from '@/types/interface/base_interface.ts';
// 接收父组件的值=====================
interface Props {
  departmentTree: TreeData[]; // 部门树形集合
  users: Array<User>; //选中的账户集合
}
const props = withDefaults(defineProps<Props>(), {});
//表格刷新函数
const loadTableList = inject<() => void>('loadTableList', () => {});
//在复选框中选择的角色Id集合
// const departmentId = ref<Number>(0);

//对话框组件======================
const dialogRef = ref(); // 对话框ref对象

//表单组件=======================
const formRef = ref();
const form = ref<Record<string, any>>({
  departmentId: 0
});
//表格组件======================
const tableRef = ref();
// 复选框选择的记录row集合
const multipleSelection = ref<User[]>([]); // 复选框选择的记录row
const handleSelectionChange = (selection: User[]) => {
  // 当选择项发生变化时会触发该事件，这里用于获取选择的记录（多选）.value可以获取所有选择了的行记录row
  multipleSelection.value = selection;
};

// 打开对话框，gong供父组件调用，传入表单对象
const openDialog = async () => {
  // 打开对话框，先初始化树形菜单
  dialogRef.value!.openDialog();
  //等待Dom刷新
  await nextTick();
  //清空上一次的表单信息
  formRef.value.resetFields();
  //默认全选所有表格，简化操作
  // tableRef.value.toggleAllSelection();
};
/**
 * 添加或移除账户的角色关
 * @param action add表示添加，remove表示移除
 */
const transferDepartment = async () => {
  if (typeof form.value.departmentId === 'undefined' || form.value.departmentId === 0) {
    ElMessage.error('请选择要转移的部门');
  } else if (multipleSelection.value.length == 0) {
    ElMessage.error('请选择要操作的账户');
  } else {
    const userIds = [];
    for (let user of multipleSelection.value) {
      userIds.push(user.id);
    }
    const formObject = {
      departmentId: form.value.departmentId,
      userIds
    };
    let resData: ResponseData = await new Request(
      urls.API_URL_BACKSTAGE_USER_MANAGE_DEPARTMENT,
      JSON.stringify(formObject)
    ).patch(); //服务端返回数据
    if (resData.success) {
      ElMessage.success(`${resData.data}个账户已经批量转移到指定部门`);
      //刷新表格
      loadTableList();
      dialogRef.value!.closeDialog();
    } else {
      ElMessage.error(resData.msg);
    }
  }
};
// 暴露组件给父容器使用
defineExpose({
  openDialog
});
</script>

<style scoped></style>
